import 'package:nylo_framework/nylo_framework.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';

class DbProvider implements NyProvider {
  static Database? _database;
  String dbName = getEnv("DATABASE_PATH", defaultValue: "db.sqlite");
  String downloadsTable = "downloads";
  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await initDB();
    return _database!;
  }

  @override
  boot(Nylo nylo) async {
    // boot your provider
    // ...
    await database; // 初始化数据库
    return nylo;
  }

  @override
  afterBoot(Nylo nylo) async {
    // Called after Nylo has finished booting
    // ...
  }

  Future<Database> initDB() async {
    final documentsDirectory = await getApplicationDocumentsDirectory();
    final path = join(documentsDirectory.path, dbName);
    NyLogger.dump("Database path: $path", 'initDB');
    return await openDatabase(
      path,
      version: 1,
      onUpgrade: (Database db, int oldVersion, int newVersion) async {
        NyLogger.dump("onUpgrade $oldVersion -> $newVersion", 'onUpgrade');
        if (oldVersion < 1) {
          // 添加缺失的列
          // await db.execute('ALTER TABLE downloads ADD COLUMN site TEXT');
        }
      },
      onCreate: (Database db, int version) async {
        NyLogger.dump("onCreate $version", 'onCreate');
        // 在这里创建表
        await db.execute('''
      CREATE TABLE ${downloadsTable} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        url TEXT,
        site TEXT,
        movie TEXT,
        name TEXT,
        save_path TEXT,
        segments TEXT,
        progress INTEGER DEFAULT 0,
        download_index INTEGER DEFAULT 0,
        status TEXT DEFAULT '解析中',
        created_at TEXT
      )
    ''');
      },
    );
  }
}
